package com.mauroleon.promotail.adapter;

import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.mauroleon.promotail.canonical.Promocion;
import com.mauroleon.promotail.mobile.PromotailApp;
import com.mauroleon.promotail.mobile.R;
import com.mauroleon.promotail.mobile.RetrieveImageTask;


public class PromocionAdapter extends ArrayAdapter<Promocion> {
	public ListActivity listaActivity;
	public Activity activity;
	public PromotailApp app;

	public PromocionAdapter(ListActivity listActivity,
			List<Promocion> promociones) {
		super(listActivity, R.layout.lista_item_promocion, promociones);
		this.listaActivity = listActivity;
	}

	public PromotailApp getApp() {
		return app;
	}

	public void setApp(PromotailApp app) {
		this.app = app;
	}

	@Override
   public View getView(int position, View convertView, ViewGroup parent) {
      
      if (convertView == null) {
         LayoutInflater inflater = (LayoutInflater) listaActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         convertView = inflater.inflate(R.layout.lista_item_promocion, parent, false);
      }

      TextView itemPromo = (TextView) convertView.findViewById(R.id.item_promo);
      TextView localPromo = (TextView) convertView.findViewById(R.id.local_promo);
      TextView nombrePromo = (TextView) convertView.findViewById(R.id.nombre_promo);
      TextView estadoPromo = (TextView) convertView.findViewById(R.id.estado_promo);
      
      ImageView image = (ImageView) convertView.findViewById(R.id.imagen_promo);
      image.setImageBitmap(BitmapFactory.decodeResource(listaActivity.getResources(), R.drawable.ic_launcher));

      Promocion item = getItem(position);

      if (item != null) {
    	 itemPromo.setText(item.getIdPromocion().toString());
    	 localPromo.setText(item.getNombreCliente().toString());
    	 nombrePromo.setText(item.getNombrePromocion().toString());
    	 estadoPromo.setText(item.getEstadoPromocion().toString());
    	 
         Bitmap bitmap = app.getImageCache().get(item.getIdPromocion());
         if (bitmap != null) {
            image.setImageBitmap(bitmap);
         } else {
            // put item ID on image as TAG for use in task
            image.setTag(item.getIdPromocion());
            // separate thread/via task, for retrieving each image
            // (note that this is brittle as is, should stop all threads in onPause)               
            //new RetrieveImageTask(image,app).execute(item.getUrlImagePromocion());
         }
      }

      return convertView;
   }}
